//
//  PostViewController.m
//  Final
//
//  Created by Lenrony on 2021/12/2.
//  Copyright © 2021 Lenrony. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "PostViewController.h"

@interface PostViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate>{
    
    int imgtypes[9];//图片类型
    
    float screen_width;
    float screen_height;
}

@property(strong, nonatomic) UIScrollView* scv;

@property(strong, nonatomic) RawUserView* ruv;
@property(strong, nonatomic) TypeSelectView* tsv;
@property(strong, nonatomic) UITextView* tv;
@property(strong, nonatomic) UIButton* btn;
@property(strong, nonatomic) UIAlertController* alert;
@property(nonatomic) BOOL isValid;

@property(strong, nonatomic) UICollectionView* imgcv;//九宫格View
@property(strong, nonatomic) UIImageView* bgv;//放大显示的图片View
@property(strong, nonatomic) UIButton* deleteBtn;//放大显示的图片View中的删除按钮
@property(strong, nonatomic) UIImageView* circle;//放大显示的视频播放按钮
@property(strong, nonatomic) UIGestureRecognizer* tapGesture;//退出放大显示的图片点击手势

@property(strong, nonatomic) UIImagePickerController* imgPicker;

@property(nonatomic) int showingImgIndex;//当前被放大的图片/视频
@property(strong, nonatomic) AVPlayer* avPlayer;//视频播放器
@property(strong, nonatomic) AVPlayerViewController* avPlayerVC;//视频播放页面

@property(strong, nonatomic) NSMutableArray* imgFilePaths;//图片或视频的文件路径
@property(strong, nonatomic) NSMutableArray* imgs;//图片数组
@property(strong, nonatomic) UIImage* addimg;//添加按钮的图片
@property(strong, nonatomic) ModelController* mc;

@end

@implementation PostViewController

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    screen_width = self.view.bounds.size.width;
    screen_height = self.view.bounds.size.height;
    
    self.mc = [ModelController getInstance];
    
    self.scv = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 50, screen_width, screen_height)];
    self.scv.contentSize = CGSizeMake(screen_width, screen_width + 550);
    [self.view addSubview:self.scv];
    
    [self.scv addSubview:self.ruv];
    [self.scv addSubview:self.tsv];
    [self.scv addSubview:self.tv];
    [self.scv addSubview:self.btn];
    self.isValid = false;
    
    //初始化
    self.imgFilePaths = [[NSMutableArray alloc]init];
    self.imgs = [[NSMutableArray alloc]init];
    self.addimg = [UIImage imageNamed:@"jiahao.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    [self loadImgCollectionViews];
}

-(void)loadImgCollectionViews
{
    //起初没有图片被展示
    self.showingImgIndex = -1;
    
    //九宫格中每一个格子布局
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((screen_width - 40) / 3, (screen_width - 40) / 3);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    
    //九宫格布局
    self.imgcv = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 400, screen_width, screen_width) collectionViewLayout:layout];
    self.imgcv.backgroundColor = [UIColor clearColor];
    self.imgcv.scrollEnabled = NO;
    self.imgcv.userInteractionEnabled = YES;
    
    //设置代理、注册
    self.imgcv.delegate = self;
    self.imgcv.dataSource = self;
    [self.imgcv registerClass:[ImgSelectCell class] forCellWithReuseIdentifier:@"SelectImgs"];
    [self.scv addSubview: self.imgcv];
    
    //放大展示到图片
    self.bgv = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width / 2, screen_height / 2, 0, 0)];
    self.bgv.alpha = 0;
    self.bgv.backgroundColor = [UIColor blackColor];
    self.bgv.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.bgv];
    
    //删除按钮
    self.deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(screen_width * 0.77, screen_height * 0.91, screen_width * 0.2, screen_width * 0.15)];
    [self.deleteBtn setTitle: @"删除" forState:UIControlStateNormal];
    [self.deleteBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.deleteBtn.titleLabel setAdjustsFontSizeToFitWidth:YES];
    [self.deleteBtn addTarget:self action:@selector(deleteImg) forControlEvents:UIControlEventTouchUpInside];
    [self.bgv addSubview: self.deleteBtn];
    
    //手势
    self.tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    
    //放大显示的视频播放按钮
    UIImage* playerIcon = [UIImage imageNamed:@"bofang.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    self.circle = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width / 2 - 50, screen_height / 2 - 50, 100, 100)];
    self.circle.center = self.bgv.center;
    self.circle.layer.cornerRadius = 50;
    self.circle.image = playerIcon;
    self.circle.backgroundColor = [UIColor lightGrayColor];
    [self.circle setUserInteractionEnabled:YES];
    UIGestureRecognizer* clickCircle = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideo)];
    [self.circle addGestureRecognizer:clickCircle];
    
    //图片选择器
    self.imgPicker = [[UIImagePickerController alloc]init];
    self.imgPicker.delegate = self;
    self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imgPicker.mediaTypes = [[NSArray alloc]initWithObjects:(NSString*)kUTTypeMovie, (NSString*)kUTTypeImage, nil];//可以选择图片和视频
}

//告诉代理返回的cell是什么样子的
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImgSelectCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SelectImgs" forIndexPath:indexPath];
    int ind = (int)indexPath.row;
    if(ind == self.imgFilePaths.count){
        [cell setImage: self.addimg];
        return cell;
    }
    
    if(imgtypes[ind] == 0){
        [cell setImage: self.imgs[ind]];
    }
    else{
        [cell setVideoImage: self.imgFilePaths[ind]];
    }
    
    return cell;
}

//一共几个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(self.imgFilePaths.count + 1 <= 9){
        return self.imgFilePaths.count + 1;
    }
    else{
        return 9;
    }
}

//选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //如果是最后一张图片，则需要设置为添加图片按钮
    int ind = (int)indexPath.row;
    if(ind == self.imgFilePaths.count){
        [self selectImg];
        return;
    }
    
    ImgSelectCell* cell = (ImgSelectCell*)[collectionView cellForItemAtIndexPath:indexPath];
    self.bgv.image = cell.img;
    self.imgcv.userInteractionEnabled = false;//让九宫格不可交互
    
    //弹出放大展示页面
    [UIView animateWithDuration:0.2 animations:^{
        self.bgv.frame = CGRectMake(0, 0, self->screen_width, self->screen_height);
        self.bgv.alpha = 1;
    } completion:^(BOOL finished) {
        //动画结束后，如果是视频，需要添加播放按钮
        if(self->imgtypes[ind] == 1){
            [self.bgv addSubview:self.circle];
        }
    }];
    self.bgv.userInteractionEnabled = true;//展示界面允许交互
    [self.bgv addGestureRecognizer:self.tapGesture];//可以点击退出
    self.showingImgIndex = ind;//当前展示的id
}

//选择图片
-(IBAction) selectImg
{
    [self presentViewController:self.imgPicker animated:YES completion:nil];
}

//成功后返回
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSString* avtype = [info objectForKey: UIImagePickerControllerMediaType];
    //图片类型
    if([avtype isEqualToString:@"public.image"]){
        UIImage* img = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self.imgs addObject:img];
        NSURL* url = [info objectForKey:UIImagePickerControllerImageURL];
        NSString* filePath = url.relativePath;
        filePath = [self.mc moveMediaToCache:filePath];
        [self.imgFilePaths addObject:filePath];
        imgtypes[self.imgFilePaths.count - 1] = 0;
    }
    //视频类型
    else{
        [self.imgs addObject:self.addimg];
        NSURL* url = [info objectForKey:UIImagePickerControllerMediaURL];
        NSString* filePath = url.relativePath;
        filePath = [self.mc moveMediaToCache:filePath];
        [self.imgFilePaths addObject:filePath];
        imgtypes[self.imgFilePaths.count - 1] = 1;
    }
    
    //重新加载
    [self.imgcv reloadData];
}

-(void)tapAction
{
    self.imgcv.userInteractionEnabled = true;//让九宫格可以交互
    
    //消失展示界面
    [UIView animateWithDuration:0.2 animations:^{
        self.bgv.frame = CGRectMake(self->screen_width / 2, self->screen_height / 2, 0, 0);
        self.bgv.alpha = 0;
        [self.circle removeFromSuperview];
    }];
    self.bgv.userInteractionEnabled = false;//展示界面禁止交互
    [self.bgv removeGestureRecognizer:self.tapGesture];//取消手势
    self.showingImgIndex = -1;
}

//播放视频
-(void)playVideo
{
    //获取视频
    NSString* filePath = self.imgFilePaths[self.showingImgIndex];
    NSURL* url = [NSURL fileURLWithPath: filePath];
    
    //打开视频播放界面开始播放
    self.avPlayer = [[AVPlayer alloc]initWithURL:url];
    self.avPlayerVC = [[AVPlayerViewController alloc]init];
    self.avPlayerVC.player = self.avPlayer;
    [self presentViewController:self.avPlayerVC animated:YES completion:nil];
    [self.avPlayer play];
}

-(void)deleteImg
{
    //修改数据
    [self.imgs removeObjectAtIndex: self.showingImgIndex];
    [self.imgFilePaths removeObjectAtIndex: self.showingImgIndex];
    for(int i = self.showingImgIndex; i < self.imgs.count; i++){
        imgtypes[i] = imgtypes[i+1];
    }
    
    //重新加载并退出
    [self.imgcv reloadData];
    [self tapAction];
}

- (void)showAlertWithTitle: (NSString*)title
                   andText: (NSString*)text
{
    self.alert = [UIAlertController alertControllerWithTitle:title message:text preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:self.alert animated:YES completion:nil];
    [self performSelector:@selector(hideAlert) withObject:self.alert afterDelay:1.5];
}

- (void)hideAlert
{
    [self.alert dismissViewControllerAnimated:YES completion:^{
        if(self.isValid){
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"请输入帖子内容";
        textView.textColor = [UIColor grayColor];
    }
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请输入帖子内容"]){
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}

-(void)postArticle
{
    if(self.tsv.type == 0){
        [self showAlertWithTitle:@"发布失败" andText:@"请选择类型！"];
        return;
    }
    
    NSString* content = self.tv.text;
    if([content isEqualToString:@""] || ([content isEqualToString:@"请输入帖子内容"] && [self.tv.textColor isEqual:[UIColor grayColor]])){
        [self showAlertWithTitle:@"发布失败" andText:@"帖子内容不能为空！"];
        return;
    }
    
    int ret = [self.mc postArticle:self.tsv.type andContent:content andImages:self.imgFilePaths];
    if(ret == -1){
        [self showAlertWithTitle:@"发布失败" andText:@"网络连接异常！"];
    }
    else if(ret == 0){
        [self showAlertWithTitle:@"发布成功" andText:@""];
        self.isValid = true;
    }
    else{
        [self showAlertWithTitle:@"发布失败" andText:@"提交帖子异常！"];
    }
}

//Lazy Load
-(RawUserView*) ruv
{
    if(_ruv == nil){
        RawUser* ru = [[RawUser alloc]initWithUID:self.mc.cur_user.u_id andName:self.mc.cur_user.name andHead:self.mc.cur_user.head_img];
        _ruv = [[RawUserView alloc]initWithRawUser:ru andViewController:self];
        _ruv.frame = CGRectMake(0, 10, screen_width / 2, 50);
    }
    return _ruv;
}

-(TypeSelectView*)tsv
{
    if(_tsv == nil){
        _tsv = [[TypeSelectView alloc]init];
        _tsv.frame = CGRectMake(0, 70, screen_width, 60);
        [_tsv setViews];
    }
    return _tsv;
}

-(UITextView*)tv
{
    if(_tv == nil){
        _tv = [[UITextView alloc]initWithFrame:CGRectMake(10, 130, screen_width - 20, 250)];
        _tv.layer.borderColor = [UIColor grayColor].CGColor;
        _tv.layer.borderWidth = 1;
        _tv.layer.cornerRadius = 8;
        _tv.text = @"请输入帖子内容";
        [_tv setFont:[UIFont systemFontOfSize:18]];
        _tv.textColor = [UIColor grayColor];
        _tv.delegate = self;
    }
    return _tv;
}

-(UIButton*)btn
{
    if(_btn == nil){
        _btn = [[UIButton alloc]initWithFrame:CGRectMake(screen_width - 90, 20, 80, 30)];
        _btn.layer.cornerRadius = 3;
        [_btn setTitle:@"发布" forState:UIControlStateNormal];
        _btn.backgroundColor = [UIColor colorWithRed:0 green:0.7f blue:0 alpha:1];
        [_btn addTarget:self action:@selector(postArticle) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn;
}

@end
